package com.lemon.smartsafetynew.ui.activity.base;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.view.FloatingActionButton;

import java.lang.reflect.Field;

/**
 * Created by Cooliean on 16/3/20.
 */
public abstract class BaseSearchFragmentActivity extends SwipeBackActivity implements SearchView.OnQueryTextListener {


    private MenuItem searchItem;
    protected SearchView mSearchView;

    protected FloatingActionButton mFab;


    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(BaseSearchFragmentActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fragment_swipe;
    }

    @Override
    protected void initViews() {
        super.initViews();


        mFab = getViewById(R.id.fab);


        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        mSearchView = new SearchView(getSupportActionBar().getThemedContext());
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        mSearchView.setIconifiedByDefault(true);
        mSearchView.setMaxWidth(1000);
        SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
        searchAutoComplete.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) showSearch(false);
            }
        });
        searchAutoComplete.setHintTextColor(getResources().getColor(R.color.material_grey_300));
        searchAutoComplete.setTextColor(getResources().getColor(R.color.colorWhite));
        searchAutoComplete.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.common_text_size));
        searchAutoComplete.setHint(getResources().getString(getSearchHintRes()));
        searchAutoComplete.setBackgroundResource(R.mipmap.edit_white_bg);

        searchAutoComplete.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) showSearch(false);
            }
        });
        try {
            // This sets the cursor
            // resource ID to 0 or @null
            // which will make it visible
            // on white background
            Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");

            mCursorDrawableRes.setAccessible(true);
            mCursorDrawableRes.set(searchAutoComplete, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }
        mSearchView.setOnQueryTextListener(this);
    }


    public abstract Fragment getFragment();

    public abstract int getSearchHintRes();


    @Override
    public void baseOnCreate(Bundle savedInstanceState) {
        super.baseOnCreate(savedInstanceState);
        if (savedInstanceState == null && getFragment() != null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.main_content, getFragment(), getFragment().getClass().getName())
                    .commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        searchItem = menu.add(android.R.string.search_go);
        searchItem.setIcon(R.mipmap.ic_search_white_24dp);

        MenuItemCompat.setActionView(searchItem, mSearchView);

        MenuItemCompat.setShowAsAction(searchItem, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

        return super.onCreateOptionsMenu(menu);
    }


    /**
     * Called when the hardware search button is pressed
     */
    @Override
    public boolean onSearchRequested() {
        showSearch(true);
        // don t show the built-in search dialog
        return false;
    }

    public void showSearch(boolean visible) {
        if (visible) MenuItemCompat.expandActionView(searchItem);
        else MenuItemCompat.collapseActionView(searchItem);
    }

    @Override
    protected void onNewIntent(Intent intent) {//这个方法父类必须要重写
        super.onNewIntent(intent);
    }

    @Override
    public boolean onQueryTextSubmit(String queryText) {
        if (mSearchView != null) {
            // 得到输入管理对象
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                // 这将让键盘在所有的情况下都被隐藏，但是一般我们在点击搜索按钮后，输入法都会乖乖的自动隐藏的。
                // 输入法如果是显示状态，那么就隐藏输入法
                imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
            }
            // 不获取焦点
            mSearchView.clearFocus();
        }
        // 修改为false，你看，你自己的代码注释里，已经对返回值做了说明呀！！！
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {//这里在点击键盘搜索的时候会变空
        return false;
    }


}
